package com.aboo.framework.util.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLHandshakeException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

/**
 * 
 * 项目名称：  ttsframe-web   
 * 类名称：  HttpClientManager   
 * 描述： 调用HTTP请求
 * @author  娄安   
 * 创建时间：  2015年11月5日 下午1:43:30 
 * 修改人：娄安    修改日期： 2015年11月5日
 * 修改备注：
 *
 */
@SuppressWarnings("all")
public class HttpClientManager {
	/**
	 * 连接池里的最大连接数
	 */
	public static final int MAX_TOTAL_CONNECTIONS = 2000;

	/**
	 * 每个路由的默认最大连接数
	 */
	public static final int MAX_ROUTE_CONNECTIONS = 2000;

	/**
	 * 连接超时时间
	 */
	public static final int CONNECT_TIMEOUT = 2000;

	/**
	 * 套接字超时时间
	 */
	public static final int SOCKET_TIMEOUT = 10000;

	/**
	 * 连接池中 连接请求执行被阻塞的超时时间
	 */
	public static final long CONN_MANAGER_TIMEOUT = 10000;

	/**
	 * http连接相关参数
	 */
	private static HttpParams parentParams;

	/**
	 * http线程池管理器
	 */
	private static PoolingClientConnectionManager cm;

	/**
	 * http客户端
	 */
	private static DefaultHttpClient httpClient;

	/**
	 * 初始化http连接池，设置参数、http头等等信息
	 */
	static {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
		schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

		cm = new PoolingClientConnectionManager(schemeRegistry);
		cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
		cm.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);

		parentParams = new BasicHttpParams();
		parentParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		parentParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
		parentParams.setParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
		parentParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIMEOUT);
		parentParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
		parentParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
		parentParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true);

		// 设置头信息,模拟浏览器
		Collection collection = new ArrayList();
		collection.add(new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)"));
		collection.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
		collection.add(new BasicHeader("Accept-Language", "zh-cn,zh,en-US,en;q=0.5"));
		collection.add(new BasicHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7"));
		// collection.add(new BasicHeader("Accept-Encoding", "gzip, deflate"));
		parentParams.setParameter(ClientPNames.DEFAULT_HEADERS, collection);

		// httpClient = new DefaultHttpClient(cm, parentParams);
		// httpClient.setHttpRequestRetryHandler(httpRequestRetryHandler);

		ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
		scheduler.scheduleAtFixedRate(new HttpConnectionClear(cm), CONNECT_TIMEOUT, CONNECT_TIMEOUT * 2,
				TimeUnit.MILLISECONDS);
		// new Thread(new HttpConnectionClear(cm,CONNECT_TIMEOUT*2)).start();
	}

	private static synchronized DefaultHttpClient getHttpClient() {
		// 请求重试处理
		HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
			public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
				// 如果超过最大重试次数，那么就不要继续了
				if (executionCount >= 5) {
					return false;
				}
				// 如果服务器丢掉了连接，那么就重试
				if (exception instanceof NoHttpResponseException) {
					return true;
				}
				// 不要重试SSL握手异常
				if (exception instanceof SSLHandshakeException) {
					return false;
				}
				HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
				boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
				// 如果请求被认为是幂等的，那么就重试
				if (idempotent) {
					return true;
				}
				return false;
			}
		};

		DefaultHttpClient httpClient = new DefaultHttpClient(cm, parentParams);
		httpClient.setHttpRequestRetryHandler(httpRequestRetryHandler);
		return httpClient;
	}

	public static String doGet(String url, Map param) {
		String html = "";
		String paramstr = "?";
		if (param != null) {
			Iterator<Map.Entry<String, String>> ie = param.entrySet().iterator();
			while (ie.hasNext()) {
				Map.Entry<String, String> en = ie.next();
				paramstr += en.getKey() + "=" + en.getValue() + "&";
			}
			if (!paramstr.equals("?")) {
				paramstr = paramstr.substring(0, paramstr.length() - 1);
			}
		}
		String httpurl = url;
		if (!paramstr.equals("?"))
			httpurl += paramstr;
		HttpGet httpGet = new HttpGet(httpurl);
		HttpResponse httpResponse;
		HttpEntity httpEntity;
		try {
			httpResponse = getHttpClient().execute(httpGet);

			StatusLine statusLine = httpResponse.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (200 != statusCode) {
				return "publicServerError";
			}
			httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				html = handleEntity(httpEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "publicServerError";
		} finally {
			if (httpGet != null) {
				httpGet.releaseConnection();
			}
		}
		return html;
	}

	public static String doPost(String url, Map param) throws Exception {
		String html = "";
		HttpPost httpost = new HttpPost(url);
		httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=UTF-8");
		httpost.addHeader("User-Agent", "Mozilla/4.0");
		try {
			// 添加参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (param != null) {
				Iterator<Map.Entry<String, String>> ie = param.entrySet().iterator();
				while (ie.hasNext()) {
					Map.Entry<String, String> en = ie.next();
					nvps.add(new BasicNameValuePair(en.getKey(), en.getValue()));
				}
			}
			httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
			HttpResponse response = getHttpClient().execute(httpost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (200 != statusCode) {
				throw new Exception();
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				return handleEntity(entity);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (httpost != null) {
				httpost.releaseConnection();
			}
		}
		return html;
	}

	private static String handleEntity(HttpEntity entity) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			String s = "";
			String result = "";
			while ((s = br.readLine()) != null) {
				result += s;
			}
			return result;
		} catch (Exception e) {
			return "publicServerError";
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (Exception e2) {
			}
		}
	}

}
